import plugin from '../../lib/plugins/plugin.js'
import fs from 'fs'
import path from 'path'

const ROOT_PATH = process.cwd();

export class DeviceSpoofer extends plugin {
  constructor() {
    super({
      name: '自定义机型',
      dsc: 'QQ自定义机型修改插件',
      event: 'message',
      priority: 5000,
      rule: [
        {
          reg: '^(自定义机型|机型修改|申请修改机型|绑定imei|自定义机型视频教程).*$',
          fnc: 'xgjx'
        }
      ]
    })
    this.configPath = path.join(ROOT_PATH, 'plugins/example/机型修改/1.json')
  }

  async readFileContent() {
    try {
      if (!fs.existsSync(this.configPath)) {
        await fs.promises.mkdir(path.dirname(this.configPath), { recursive: true })
        await fs.promises.writeFile(this.configPath, '{}', 'utf8')
      }
      const content = await fs.promises.readFile(this.configPath, 'utf8')
      return JSON.parse(content)
    } catch (error) {
      console.error('读取文件失败:', error)
      return {}
    }
  }

  async writeFileContent(content) {
    try {
      await fs.promises.writeFile(this.configPath, JSON.stringify(content, null, 2))
      return true
    } catch (error) {
      console.error('写入文件失败:', error)
      return false
    }
  }

  async makeRequest(url, method, data = null, headers = {}) {
    try {
      const options = {
        method,
        headers: {
          'Content-Type': 'application/json',
          ...headers
        }
      }
      if (data) {
        options.body = JSON.stringify(data)
      }
      const response = await fetch(url, options)
      const result = await response.text()
      return result
    } catch (error) {
      console.error('请求失败:', error)
      return null
    }
  }

  async sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms))
  }

  async wk(content) {
    return content
  }

  async xgjx(e) {
    if (e.msg == "自定义机型") {
      const a = `
(1)打开链接，点击设备信息
(2)复制对应的IMEI码后绑定
(3)安卓IMEI码为androidID
(4)苹果的IMEI码为msf_identifier
↑↑↑↑获取imei方法↓↓↓
(5)申请修改机型
(6)绑定imei IMEI
(7)机型修改 机型
(8)机型修改>默认设置iPhone 16 Pro Max
(8)未生效就是IMEI码复制错了
(9)自定义机型视频教程
`
      const js = await this.wk(a)
      e.reply(js, true)
      e.reply("https://1105583577.urlshare.cn", true)
      return
    }

    if (e.msg == "自定义机型视频教程") {
      const dw = "https://suo.yt/bDqLhLI"
      const u = `http://q1.qlogo.cn/g?b=qq&nk=${e.user_id}&s=640`
      const data = `fm=${u}&tz=${dw}&dbt=自定义机型&xbt=点击卡片查看视频教程`
      e.reply(segment.json(await this.makeRequest('https://api.s01s.cn/API/ark_tz2/', "POST", data, {
        'Content-Type': 'application/x-www-form-urlencoded'
      })))
      return
    }

    if (e.msg == "申请修改机型") {
      const a = "https://api.s01s.cn/API/gjx/?type=2"
      const login = JSON.parse(await this.makeRequest(a, "GET"))
      const message = [
        segment.image(login.img),
        "35s请尽快登录哦~否则会过期的!\n可以直接点开识别扫码",
      ]
      await e.reply(message, true)
      let id = `https://api.s01s.cn/API/gjx/?type=3&md5=${login.id}`
      let check = ""
      let counter = 0
      while (true) {
        if (counter === 7) {
          this.e.reply('时间到了，验证失败', true)
          break
        } else {
          counter++
        }
        check = JSON.parse(await this.makeRequest(id, "GET"))
        if (check.code != 66 && check.code != 67) {
          await e.reply(check.msg, true)
          break
        }
        await this.sleep(5000)
      }
      if (check.code == 0) {
        const k = await this.readFileContent()
        if (!k[e.user_id]) {
          k[e.user_id] = []
        }
        if (!Array.isArray(k[e.user_id])) {
          k[e.user_id] = [k[e.user_id]]
        }
        k[e.user_id][0] = check.uin
        await this.writeFileContent(k)
      }
      return
    }

    const t = e.msg.match(/(机型修改|绑定imei)/)
    if (t) {
      const k = await this.readFileContent()

      if (t[1] == "绑定imei") {
        const imei = e.msg.slice(t[1].length).trim()
        if (!k[e.user_id]) {
          k[e.user_id] = []
        }
        if (!Array.isArray(k[e.user_id])) {
          k[e.user_id] = [k[e.user_id]]
        }
        k[e.user_id][1] = imei
        await this.writeFileContent(k)
        e.reply(`绑定imei成功\nimei：${imei}`, true)
        return
      }

      if (t[1] == "机型修改") {
        if (!k[e.user_id] || !k[e.user_id][0]) {
          e.reply("没有申请修改机型", true)
          return
        }
        if (!k[e.user_id][1]) {
          e.reply("没有绑定imei", true)
          return
        }

        let model = "iPhone 16 Pro Max" // 默认机型
        if (e.msg.length > 4) {
          model = e.msg.slice(4).trim()
        }

        const a = `https://api.s01s.cn/API/gjx/?type=1&uin=${k[e.user_id][0]}&imei=${k[e.user_id][1]}&model=${encodeURIComponent(model)}`
        const xg = await this.makeRequest(a, "GET")
        e.reply(xg, true)
        return
      }
    }
  }
}